package com.shopmall.manager.task;

import cn.hutool.core.date.DateUtil;
import com.shopmall.manager.mapper.OrderInfoMapper;
import com.shopmall.manager.mapper.OrderStatisticsMapper;
import com.shopmall.model.entity.order.OrderStatistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class OrderStatisticsTask {
    // 注解：@Scheduled + cron 表达式
    // cron表达式设置执行规则
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderStatisticsMapper orderStatisticsMapper;

    // 每天凌晨2，查询前一天统计数，添加到结果表
    @Scheduled(cron = "0 0 2 * * ? ")
//    @Scheduled(cron = "0/10 * * * * ? ") //测试
    public void orderTotalAmountStatistics() {
        // 获取前一天日期
        String createDate = DateUtil.offsetDay(new Date(), -1).toString("yyyy-MM-dd");
        // 获取前一天日期数据进行分组统计出前一天交易金额
        OrderStatistics orderStatistics = orderInfoMapper.selectStatisticsByDate(createDate);
        // 把统计之后的数据，添加到统计结果表中
        if (orderStatistics != null) {
            orderStatisticsMapper.insert(orderStatistics);
        }
    }
}
